/*
	订单详情
	订单信息修改
*/


//登录信息
var adminLoginedInfo = Cookies.getJSON('kplus_ad_logined_info');

//存储
var KEEP_DATA = {}
//快递字典
var KEEP_COM_DATA = {}
// 获取订单详细信息
// 获取支持的快递公司
// 针对已付款订单可进行发货修改
var countriesAndRegions = [
    {name:"台灣",abbr:"TW",lang:"zh_TW"},
    {name:"香港",abbr:"HK",lang:"en_GB"},
/*  {name:"中国大陆",abbr:"CN",lang:"zh_CN"},
*/
];
const abbrList = {
	'TW': {
		name: '台灣',
		abbr:"TW",
		lang:"zh_TW"
	},
	'HK': {
		name:"香港",
		abbr:"HK",
		lang:"en_GB"
	}
}

//dom
$(function(){
	layui.use(['layer', 'form', 'laydate', 'table'], function(){

		var layer = layui.layer, form = layui.form, laydate = layui.laydate, table = layui.table;

		// ajax data
		var ajaxData = { aId: adminLoginedInfo.aId, aToken: adminLoginedInfo.aToken };

		function getOrderDetail(ajaxData){
			/*
				获取订单详细信息
			*/
			var _ajaxData = $.extend({oId: getParam('oid')}, ajaxData);
			var loadIndex = layer.load(1, { shade: [0.5, '#000'] });

			$.ajax({
				url: BASE_SERVICEURL + URlS.order,
				type:'GET',
				data: _ajaxData,
				success: function(responseData){
					if(responseData.msg.code == 200){
						//console.log(responseData)
						initFormData(responseData.data[0]);
						//商品列表
						productData(responseData.data[0].product_data)
						layer.close(loadIndex);
					}else{
						layer.close(loadIndex);
						layer.msg(responseData.msg.msg, {time: 2000});
					}
				},
				error: function(responseData){
					layer.close(loadIndex);
					layer.msg(MESSAGES.service_error, {time: 2000});
					location.href = './500.html';
				}
			});
		}
		//快递信息
		var expCom = $('#expCom');
		EXP_COM.map(function(item, i){
			var opt = '<option value="'+ item.no +'">'+ item.com +'</option>';
			KEEP_COM_DATA[item.no] = item.com;
			expCom.append(opt);
		});
		
		//table 表单
		function productData(data){
			var pd = data;
			var tableData = [];
			pd.map(function(item, i){
				tableData.push({
					thumbnail: item.p_img[0],
					brand: item.p_brand,
					series: item.p_series,
					name: item.p_name['tw'],
					color: item.p_color,
					size: item.p_size,
					count: item.p_count,
					amount: item.amount
				})
			});
			table.render({
				elem: '#tableContent',
				height: 580,
				limit: 10, //分页
				page: true,
				cols:[[ //表头
					{field: 'thumbnail', title: '缩略图', templet: function(d){  //自定义模板
						//console.log(d)
						return '<img src="' + d.thumbnail + '?imageView2/1/w/90/h/90/q/75|imageslim" alt="商品缩略图">'
					}},
					{field: 'brand', title: '品牌', sort: true},
					{field: 'series', title: '系列', sort: true, width:60} ,
					{field: 'name', title: '名称'},
					{field: 'color', title: '颜色'},			
					{field: 'size', title: '尺寸'},
					{field: 'count', title: '数量', sort: true},
					{field: 'amount', title: '总价', sort: true},
				]],
				data:tableData
			});
		}

		//表单赋值
		function initFormData(data){
			var d = data;
			var formInitValue = {
				orderId: d.o_id,
				payNo: d.order_pay_no || '',
				tradeNo: d.trade_no || '',
				createTime: formatTime(d.format_time),
				payTime: d.pay_status_return_time || '',
				payment: d.payment,
				currency: d.currency,
				payAmount: d.pay_return_amount,
				payMethod: d.pay_method,
				expCom: d.express_com,
				expNo: d.express_num,
				orderStatus: d.status,
				sendName: d.send_name,
				sendAddr: '(' + abbrList[d.abbr].name + ')' + d.send_addr,
				zipCode: d.zip_code,
				sendPhone: d.send_phone,
				sendMail: d.send_mail,
				freight: 'NT$ ' + d.freight['tw']
			}
			//持久化
			KEEP_DATA = formInitValue;
			//表单赋值
		    form.val("order-data-form", formInitValue);
		    form.render();
		}
		// 获取订单信息
		getOrderDetail(ajaxData);
		
		// 发送邮件
		function sendMailToUser(sendData){
			/*
				sendData = {
					uMail: 'xxxxxx',
					wId: 'xxczxcz'
				}
			*/
			var _ajaxData = $.extend({}, sendData, ajaxData);

			$.ajax({
				url: BASE_SERVICEURL + URlS.order_mail,
				type:'POST',
				data: _ajaxData,
				success: function(responseData){
					if(responseData.msg.code == 200){
						console.log(responseData.data.data)
					}else{
						layer.msg(responseData.msg.msg, {time: 2000});
					}
				},
				error: function(responseData){
					layer.msg(MESSAGES.service_error, {time: 2000});
					location.href = './500.html';
				}
			});


		}

		// 确认修改
		form.on('submit(modify)', function(data){
			layer.confirm(MESSAGES.confirm_modify_order_status, {title:'提示'}, function(index){
				//console.log(data.field);
				var f = data.field;
				// 判断订单状态
				if(Number(f.orderStatus) <= Number(KEEP_DATA.orderStatus)){
					// 并不能不跟新或者状态倒退
					layer.msg('订单状态需没更新或者状态倒退', {time: 2000})
					return;
				};
				//废止需要提示
				if(f.orderStatus == '5'){
					layer.confirm('确认将订单废止？该操作不可逆！', {title:'提示'}, function(index){
						//执行更新 -- 由后端判断权限
						updataOrder({
							status: f.orderStatus
						})
						layer.close(index);
					})
				}
				//退款需要提示
				if(f.orderStatus == '4'){
					layer.confirm('确认将订单退款？该操作不可逆！', {title:'提示'}, function(index){
						//执行更新 -- 由后端判断权限
						updataOrder({
							status: f.orderStatus
						})
						layer.close(index);
					})
				}
				// 状态更新 -- 发货
				if(f.orderStatus == '2'){
					if(!f.expCom || !f.expNo){
						layer.msg('需要快递公司信息及快递单号', {time: 2000})
						return;
					}else{
						//执行更新
						updataOrder({
							status: f.orderStatus,
							name: KEEP_COM_DATA[f.expCom],
							com: f.expCom,
							no: f.expNo
						})
					}
				}
				// 已收货
				if(f.orderStatus == '3'){
					if(KEEP_DATA.orderStatus == '2'){
						//执行更新
						updataOrder({
							status: f.orderStatus
						})
					}else{
						layer.msg('订单不是发货状态，无法更新收货状态！', {time: 2000});
						return;
					}
				}
				layer.close(index); //关闭询问框
			});

			return false;
		})

		function updataOrder(newOrderData){
			/*
				修改订单状态
			*/
			var _ajaxData = $.extend({oId: getParam('oid')}, newOrderData, ajaxData);
			var loadIndex = layer.load(1, { shade: [0.5, '#000'] });

			$.ajax({
				url: BASE_SERVICEURL + URlS.order,
				type:'POST',
				data: _ajaxData,
				success: function(responseData){
					if(responseData.msg.code == 200){
						//console.log(responseData)
						if(_ajaxData.status == '2'){
							// 发货
							sendMailToUser({
								wId: 'kpMail20181210170548',
								uMail: KEEP_DATA['sendMail']
							})
						}
						if(_ajaxData.status == '4'){
							// 退货
							sendMailToUser({
								wId: 'kpMail20181210170235',
								uMail: KEEP_DATA['sendMail']
							})
						}
						window.location.reload();
					}else{
						layer.close(loadIndex);
						layer.msg(responseData.msg.msg, {time: 2000});
					}
				},
				error: function(responseData){
					layer.close(loadIndex);
					layer.msg(MESSAGES.service_error, {time: 2000});
					location.href = './500.html';
				}
			});


		}
	})
})






















